// pages/my/my.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 获取验证码的字体颜色
    codeColor: '#999',
    codeText: '获取验证码',
    canClick: true,
    smsCode: '3819',
    userinfo: {},
    username: '13800000001'
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  // 手机号输入事件
  handlePhone: function(e) {
    let username = e.detail.value;
    let reg = /^1[345789]\d{9}$/;
    if (reg.test(username)) {
      // 可以点击
      this.setData({
        username,
        codeColor: '#2396ff',
        canClick: true
      })
    } else {
       // 不可以点击
      this.setData({
        username,
        canClick: false,
        codeColor: '#999'
      })
    }
    
  },
  // 验证码输入事件
  handleCode: (e) => {
    this.setData({
      smsCode: e.detail.value
    })
  },

  getCode: function() {
    if (!this.data.canClick) return false;
    let url = '/user/getSmsCode';
    let params = {
      phone: this.data.username
    }
    let count = 10;
    let timer = setInterval(() => {
      count--;
      if (count === 0) {
        this.setData({
          codeColor: '#2396ff',
          canClick: true,
          codeText: '获取验证码'
        })
        clearInterval(timer);
      } else {
        this.setData({ 
          codeColor: '#999',
          canClick: false,
          codeText: count + '秒' 
       })
      }
    }, 1000);
    app.ajax(url, params,res=> {
      wx.showModal({
        showCancel: false,
        content: `验证码已发送到尾号为${res.phone}的手机`,
      })
    })
  },


  // 倒计时
  countDown: function(time,callback) {
    setTimeout(()=> {
      time--;
      callback(time);
    },1000);
  },

  login: function () {
    wx.login({
      success: (res) => {
        const url = '/user/login';
        const data = {
          smsCode: this.data.smsCode,
          code: res.code,
          username: this.data.username,
        }
        app.ajax(url, data, res => {
          wx.showModal({
            // title: '',
            content: '登录成功',
            showCancel: false,
            success:()=> {
              // 从哪里来回哪里去
              wx.navigateBack({
                delta: 1
              })
            }
          })
          // 成功之后把token保存起来
          wx.setStorageSync('token', res.data.token);
        });;
      }
    });
  }
})